import React, { useEffect, useState, useCallback } from 'react';
import {
  Form,
  Input,
  InputNumber,
  Select,
  Switch,
  Card,
  Space,
  Button,
  Tooltip,
  Alert,
  Row,
  Col,
  Divider,
  Tag,
  AutoComplete,
  message
} from 'antd';
import {
  InfoCircleOutlined,
  ReloadOutlined,
  SaveOutlined,
  ClearOutlined,
  ThunderboltOutlined,
  CopyOutlined,
  ImportOutlined,
  ExportOutlined
} from '@ant-design/icons';
import { PromptVariable, PromptVariableValue } from '@/types/prompt';
import { variableManager } from '@/services/variable.service';
import './style.css';

const { TextArea } = Input;
const { Option } = Select;

interface VariableFormProps {
  variables: PromptVariable[];
  values?: Record<string, PromptVariableValue>;
  onChange?: (values: Record<string, PromptVariableValue>) => void;
  onSubmit?: (values: Record<string, PromptVariableValue>) => void;
  onValidate?: (valid: boolean, errors: string[]) => void;
  showActions?: boolean;
  layout?: 'horizontal' | 'vertical';
  className?: string;
}

const VariableForm: React.FC<VariableFormProps> = ({
  variables = [],
  values: initialValues = {},
  onChange,
  onSubmit,
  onValidate,
  showActions = true,
  layout = 'vertical',
  className = ''
}) => {
  const [form] = Form.useForm();
  const [errors, setErrors] = useState<string[]>([]);
  const [suggestions, setSuggestions] = useState<Record<string, string[]>>({});
  const [hasChanges, setHasChanges] = useState(false);

  // 初始化表单值
  useEffect(() => {
    const initialFormValues = variableManager.generateInitialValues(variables);
    const mergedValues = { ...initialFormValues, ...initialValues };
    form.setFieldsValue(mergedValues);
    
    // 加载变量建议值
    const newSuggestions: Record<string, string[]> = {};
    variables.forEach(v => {
      const suggested = variableManager.getSuggestedValues(v.name);
      if (suggested.length > 0) {
        newSuggestions[v.name] = suggested;
      }
    });
    setSuggestions(newSuggestions);
  }, [variables, initialValues, form]);

  // 处理表单值变化
  const handleValuesChange = useCallback((changedValues: any, allValues: any) => {
    setHasChanges(true);
    
    // 验证变量
    const validation = variableManager.validateVariables(variables, allValues);
    setErrors(validation.errors);
    
    if (onValidate) {
      onValidate(validation.valid, validation.errors);
    }
    
    if (onChange) {
      onChange(allValues);
    }
  }, [variables, onChange, onValidate]);

  // 提交表单
  const handleSubmit = useCallback(() => {
    form.validateFields().then(values => {
      const validation = variableManager.validateVariables(variables, values);
      
      if (validation.valid) {
        if (onSubmit) {
          onSubmit(values);
          setHasChanges(false);
          message.success('变量已提交');
        }
      } else {
        message.error('请修正错误后再提交');
      }
    }).catch(error => {
      console.error('Form validation failed:', error);
      message.error('表单验证失败');
    });
  }, [form, variables, onSubmit]);

  // 重置表单
  const handleReset = useCallback(() => {
    const initialFormValues = variableManager.generateInitialValues(variables);
    form.setFieldsValue(initialFormValues);
    setHasChanges(false);
    setErrors([]);
    message.info('已重置为默认值');
  }, [form, variables]);

  // 清空表单
  const handleClear = useCallback(() => {
    form.resetFields();
    setHasChanges(false);
    setErrors([]);
    message.info('已清空所有值');
  }, [form]);

  // 应用建议值
  const handleApplySuggestion = useCallback((variableName: string, value: string) => {
    form.setFieldValue(variableName, value);
    setHasChanges(true);
    message.success(`已应用建议值: ${value}`);
  }, [form]);

  // 复制变量值
  const handleCopyValues = useCallback(() => {
    const values = form.getFieldsValue();
    const json = JSON.stringify(values, null, 2);
    navigator.clipboard.writeText(json).then(() => {
      message.success('变量值已复制到剪贴板');
    });
  }, [form]);

  // 导入变量值
  const handleImportValues = useCallback(() => {
    navigator.clipboard.readText().then(text => {
      try {
        const importedValues = JSON.parse(text);
        form.setFieldsValue(importedValues);
        setHasChanges(true);
        message.success('变量值已导入');
      } catch (error) {
        message.error('导入失败：剪贴板内容不是有效的JSON');
      }
    });
  }, [form]);

  // 渲染变量输入字段
  const renderVariableField = (variable: PromptVariable) => {
    const fieldRules = [];
    
    if (variable.required) {
      fieldRules.push({ required: true, message: `${variable.name} 是必需的` });
    }
    
    if (variable.validation) {
      fieldRules.push({
        pattern: new RegExp(variable.validation),
        message: `${variable.name} 格式不正确`
      });
    }

    const fieldProps: any = {
      name: variable.name,
      label: (
        <Space>
          <span>{variable.name}</span>
          {variable.required && <Tag color="red" style={{ fontSize: 10 }}>必需</Tag>}
          {variable.description && (
            <Tooltip title={variable.description}>
              <InfoCircleOutlined style={{ color: '#8c8c8c' }} />
            </Tooltip>
          )}
        </Space>
      ),
      rules: fieldRules,
      initialValue: variable.defaultValue
    };

    switch (variable.type) {
      case 'string':
        const stringSuggestions = suggestions[variable.name] || [];
        
        return (
          <Form.Item {...fieldProps}>
            {variable.validation?.includes('\\n') || variable.name.includes('description') ? (
              <TextArea
                rows={4}
                placeholder={`请输入${variable.description || variable.name}`}
                showCount
                maxLength={variable.max}
              />
            ) : stringSuggestions.length > 0 ? (
              <AutoComplete
                options={stringSuggestions.map(s => ({ value: s }))}
                placeholder={`请输入${variable.description || variable.name}`}
              >
                <Input maxLength={variable.max} />
              </AutoComplete>
            ) : (
              <Input
                placeholder={`请输入${variable.description || variable.name}`}
                maxLength={variable.max}
              />
            )}
          </Form.Item>
        );

      case 'number':
        return (
          <Form.Item {...fieldProps}>
            <InputNumber
              style={{ width: '100%' }}
              min={variable.min}
              max={variable.max}
              placeholder={`请输入${variable.description || variable.name}`}
              precision={0}
            />
          </Form.Item>
        );

      case 'select':
        return (
          <Form.Item {...fieldProps}>
            <Select
              placeholder={`请选择${variable.description || variable.name}`}
              allowClear={!variable.required}
            >
              {variable.options?.map(option => (
                <Option key={option} value={option}>
                  {option}
                </Option>
              ))}
            </Select>
          </Form.Item>
        );

      case 'boolean':
        return (
          <Form.Item {...fieldProps} valuePropName="checked">
            <Space>
              <Switch />
              <span>{variable.description || variable.name}</span>
            </Space>
          </Form.Item>
        );

      default:
        return null;
    }
  };

  // 按类型分组变量
  const groupedVariables = variables.reduce((groups, variable) => {
    const type = variable.type;
    if (!groups[type]) {
      groups[type] = [];
    }
    groups[type].push(variable);
    return groups;
  }, {} as Record<string, PromptVariable[]>);

  const getTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      string: '文本变量',
      number: '数字变量',
      select: '选择变量',
      boolean: '开关变量'
    };
    return labels[type] || type;
  };

  if (variables.length === 0) {
    return (
      <Card className={`variable-form-container ${className}`}>
        <Empty
          description="当前模板没有定义变量"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </Card>
    );
  }

  return (
    <Card
      className={`variable-form-container ${className}`}
      title={
        <Space>
          <span>变量填写</span>
          {hasChanges && <span className="unsaved-indicator">●</span>}
          <Tag color="blue">{variables.length} 个变量</Tag>
        </Space>
      }
      extra={
        showActions && (
          <Space>
            <Tooltip title="复制值">
              <Button
                size="small"
                icon={<CopyOutlined />}
                onClick={handleCopyValues}
              />
            </Tooltip>
            <Tooltip title="导入值">
              <Button
                size="small"
                icon={<ImportOutlined />}
                onClick={handleImportValues}
              />
            </Tooltip>
          </Space>
        )
      }
    >
      {errors.length > 0 && (
        <Alert
          message="验证错误"
          description={
            <ul className="error-list">
              {errors.map((error, index) => (
                <li key={index}>{error}</li>
              ))}
            </ul>
          }
          type="error"
          showIcon
          closable
          style={{ marginBottom: 16 }}
        />
      )}

      <Form
        form={form}
        layout={layout}
        onValuesChange={handleValuesChange}
        onFinish={handleSubmit}
        className="variable-form"
      >
        {layout === 'vertical' ? (
          // 垂直布局 - 按类型分组
          Object.entries(groupedVariables).map(([type, vars]) => (
            <div key={type}>
              <Divider orientation="left">{getTypeLabel(type)}</Divider>
              <Row gutter={[16, 0]}>
                {vars.map(variable => (
                  <Col key={variable.name} xs={24} sm={12} lg={8}>
                    {renderVariableField(variable)}
                  </Col>
                ))}
              </Row>
            </div>
          ))
        ) : (
          // 水平布局 - 不分组
          <Row gutter={[16, 0]}>
            {variables.map(variable => (
              <Col key={variable.name} span={24}>
                {renderVariableField(variable)}
              </Col>
            ))}
          </Row>
        )}

        {showActions && (
          <>
            <Divider />
            <Form.Item className="form-actions">
              <Space>
                <Button
                  type="primary"
                  icon={<ThunderboltOutlined />}
                  onClick={handleSubmit}
                  loading={false}
                >
                  应用变量
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={handleReset}
                >
                  重置默认
                </Button>
                <Button
                  icon={<ClearOutlined />}
                  onClick={handleClear}
                >
                  清空
                </Button>
              </Space>
            </Form.Item>
          </>
        )}
      </Form>

      {/* 变量建议 */}
      {Object.keys(suggestions).length > 0 && (
        <div className="variable-suggestions">
          <Divider orientation="left">常用值建议</Divider>
          {Object.entries(suggestions).map(([name, values]) => (
            <div key={name} className="suggestion-item">
              <span className="suggestion-name">{name}:</span>
              <Space wrap>
                {values.map(value => (
                  <Tag
                    key={value}
                    className="suggestion-tag"
                    onClick={() => handleApplySuggestion(name, value)}
                  >
                    {value}
                  </Tag>
                ))}
              </Space>
            </div>
          ))}
        </div>
      )}
    </Card>
  );
};

// 导入Empty组件
import { Empty } from 'antd';

export default VariableForm;